package com.example.dynamicdatasource.config;

import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.example.dynamicdatasource.config.datasource.LazyDynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties({DynamicDataSourceProperties.class, ProvinceDbProperties.class})
public class DynamicDataSourceConfig {

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    @Primary
    public DataSource dataSource(DynamicDataSourceProperties properties,
                                 @Qualifier("hikariDataSourceCreator") DataSourceCreator dataSourceCreator,
                                 ProvinceDbProperties provinceDbProperties,
                                 @Value("${db-template.url-pattern}") String urlPattern,
                                 @Value("${db-template.username}") String username,
                                 @Value("${db-template.password}") String password,
                                 @Value("${db-template.driver-class-name}") String driverClassName) {

        // 获取主数据源配置
        Map<String, DataSource> dataSources = properties.getDatasource().entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> dataSourceCreator.createDataSource(entry.getValue())
                ));

        // 预先加载不需要懒加载的数据源
        Map<String, ProvinceDbProperties.ProvinceDbConfig> eagerLoadConfigs = provinceDbProperties.getEagerLoadConfigs();
        eagerLoadConfigs.forEach((dsKey, config) -> {
            if (!dataSources.containsKey(dsKey)) {
                String url = urlPattern.replace("{dbName}", config.getName());

                // 构建数据源属性对象（修正部分）
                DataSourceProperty property = new DataSourceProperty();
                property.setPoolName(dsKey);
                property.setUrl(url);
                property.setUsername(username);
                property.setPassword(password);
                property.setDriverClassName(driverClassName);

                DataSource dataSource = dataSourceCreator.createDataSource(property);
                dataSources.put(dsKey, dataSource);
                System.out.println("预加载数据源: " + dsKey);
            }
        });

        // 创建带懒加载功能的动态数据源
        LazyDynamicDataSource dataSource = new LazyDynamicDataSource(
                provinceDbProperties,
                dataSourceCreator,
                urlPattern,
                username,
                password,
                driverClassName,
                dataSources
        );

        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());

        return dataSource;
    }
}
